package insta.project.remote;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class HttpRequest {
	private static HttpRequest instance = null;

	protected HttpRequest() {
		// Exists only to defeat instantiation.
	}

	public static HttpRequest getInstance() {
		if (instance == null) {
			instance = new HttpRequest();
		}
		return instance;
	}

	private String[][] strarrRemoteData = null;

	public static String GET(String strRequestURI) throws Exception {
		BufferedReader in = null;
		String page = "";
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(strRequestURI));
			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			page = sb.toString();
			page = page.replaceAll("<raw>", "").trim();
		} finally {
			if (in != null) {
				try {
					in.close();
					return page;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return page;
	}

	public String[][] getMusicListArray() throws Exception {
		// Check if we already got value in memory
		if (this.strarrRemoteData != null && this.strarrRemoteData.length > 0) {
			return this.strarrRemoteData;
		}
		// Get current ID list
		String strRemoteContent = HttpRequest
				.GET("http://www.freebangers.com/androidquery/");
		String[] remoteContent = strRemoteContent.split(";");
		String[][] finalResult = new String[remoteContent.length][5];
		for (int i = 0; i < remoteContent.length; i++) {
			String[] musicData = remoteContent[i].split("#");
			if (musicData.length == 5) {
				finalResult[i] = musicData;
			}
		}
		this.strarrRemoteData = finalResult;
		return finalResult;
	}

}
